import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import './styles/main.css'
import { createPinia } from 'pinia'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { webAPI } from './utils/webAPI'

// 检查是否在 Electron 环境中运行
const isElectron = navigator.userAgent.includes('Electron')

// 如果在 Web 环境中运行，提供模拟的 Electron API
if (!isElectron) {
  (window as any).electronAPI = webAPI
}

const app = createApp(App)

for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

//这里增加一个router钩子， 判断token信息
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.meta.requiresAuth) {
    if (token) {
      next()
    } else {
      if (to.path === '/login') {
        next()
      } else {
        next('/login')
      }
    }
  } else {
    // 判断如果是登录页， 存在token的情况直接进入首页
    if (to.path === '/login') {
      if (token) {
        next('/')
      } else {
        next()
      }
    } else {
      next()
    }
  }
})

app.use(ElementPlus, {
  locale: zhCn,
})
app.use(router)
app.use(createPinia())
app.mount('#app')